#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
系统配置
Created by gongp on 2017/9/9.
"""

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json

from django.shortcuts import render, reverse, redirect
from django.contrib.auth import get_user
from django.contrib.auth.decorators import login_required, permission_required

from django.http import HttpResponse, HttpResponseRedirect

from smAdmin.models import SmadminConfig, SmplatConfig, WxmpConfig

from smAdmin.jqgrid import JqGrid

import logging

logger = logging.getLogger('smAdmin')


# ------------- 公众号配置 ------------------
class WxmpConfigGrid(JqGrid):
	model = WxmpConfig  # could also be a queryset
	pager_id = "#wxmp-config-grid-pager"
	fields = ['id',
			  'label',
			  'name',
			  'value',
			  'vtype',
			  'description',
			  'input_options',
			  # 'update_time',
			  'myac'
			  ]

	url = '/smAdmin/sysconf/wxmp_conf_list'
	editurl = '/smAdmin/sysconf/wxmp_conf_edit'
	caption = u'公众号配置'
	colmodel_overrides = {
		'id': {'key': True, 'width': 20, "hidden": True},
		'label': {
			"label": u"标题",
			"sortable": False,

			"search": True,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'text',
			"editoptions": {"size": "32", "maxlength": "64"},

			'width': 100
		},

		'name': {
			"label": u"参数名",
			"sortable": False,

			"search": True,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'text',
			"editoptions": {"size": "32", "maxlength": "64"},

			'width': 100
		},

		'value': {
			"label": u"参数值",
			"sortable": False,

			"search": False,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'textarea',
			"editoptions": {"rows": "5", "cols": "60"},

			'width': 100
		},

		'vtype': {
			"label": u"参数类型",
			# 排序
			"sortable": False,
			"sorttype": 'string',
			# 搜索
			"search": True,
			"stype": "select",
			"searchoptions": {"sopt": ['eq', ], "value": "string:字符串;json:json;int:整数;float:浮点"},
			# 编辑
			'editable': True,
			"edittype": 'select',
			"editoptions": {"value": "string:字符串;json:json;int:整数;float:浮点"},
			# 其他
			'width': 100
		},

		'description': {
			"label": u"描述",
			"sortable": False,

			"search": False,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'textarea',
			"editoptions": {"rows": "5", "cols": "60"},

			'width': 100
		},

		'input_options': {
			"label": u"输入框配置",
			"sortable": False,

			"search": False,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'textarea',
			"editoptions": {"rows": "5", "cols": "60"},

			'width': 100
		},

		'update_time': {
			"label": u"更新时间",
			"sortable": False,

			"search": True,
			"sorttype": 'date',
			"searchoptions": {"sopt": ['le', 'lt', 'gt', 'ge']},

			'editable': False,
			# "edittype": 'text',
			# "editoptions": {"size": "20", "maxlength": "40"},

			'width': 100
		},

		'myac': {
			"label": u"操作",
			'editable': False,
			"width": 80,
			"fixed": True,
			"sortable": False,
			"search": False,
			"resize": False,
			"formatter": 'actions',
			"formatoptions": {"keys": True, "delbutton": True, }
		}
	}


@login_required(login_url="/smAdmin/login")
@permission_required(['submenu.sysconf.wxmp_config', ])
def wxmp_config(request):
	"""
	扫码记录
	:param request:
	:return:
	"""
	grid = WxmpConfigGrid()
	context = {
		"grid_config": grid.get_config(),
	}
	return render(request, "smAdmin/sysconf/wxmp_config.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['sysconf.wxmp_config.list', ])
def wxmp_config_list(request):
	grid = WxmpConfigGrid()
	return HttpResponse(grid.get_json(request), content_type="application/json")


@login_required(login_url="/smAdmin/login")
@permission_required(['sysconf.wxmp_config.add', 'sysconf.wxmp_config.edit', 'sysconf.wxmp_config.del'])
def wxmp_config_edit(request):
	"""
	编辑
	:param request:
	:return:
	"""
	grid = WxmpConfigGrid()

	oper = request.POST.get('oper')
	id = request.POST.get('id')
	user = get_user(request)

	if oper == 'edit':
		if not user.has_perm("sysconf.wxmp_config.edit"):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.edit_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'add':
		if not user.has_perm("sysconf.wxmp_config.add"):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.add_object(request):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'del':
		if not user.has_perm("sysconf.wxmp_config.del"):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.delete_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)

	return HttpResponse(content_type="application/x-javascript", status=406)


@login_required(login_url="/smAdmin/login")
@permission_required(['sysconf.wxmp_config.edit', ])
def wxmp_config_detail(request):
	"""
	扫描记录详情
	:param request:
	:return:
	"""
	id = request.GET.get('id')

	wxmpConfig = WxmpConfig.objects.get(id=id)

	try:
		value_config = json.loads(wxmpConfig.input_options)
	except:
		value_config = {}
		logger.exception("")

	input_type = value_config.get("type", "textarea")

	field_info = {
		"fields": [
			{"name": "id", "label": u"Id", "value": wxmpConfig.id},
			{"name": "label", "label": u"标题", "value": wxmpConfig.label},
			{"name": "name", "label": u"参数名", "value": wxmpConfig.name},
			{"name": "value", "label": u"参数值", "value": wxmpConfig.value},
			{"name": "vtype", "label": u"值类型", "value": wxmpConfig.vtype},
			{"name": "description", "label": u"描述", "value": wxmpConfig.description},
			{"name": "input_options", "label": u"输入框配置", "value": wxmpConfig.input_options},
			{"name": "update_time", "label": u"更新时间", "value": wxmpConfig.update_time}
		],
		"input_type": input_type,
		"value_config": value_config,
		"value_data": wxmpConfig.value,
	}

	context = {
		"field_info": field_info,
	}
	return render(request, "smAdmin/sysconf/wxmp_config_detail.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['sysconf.wxmp_config.edit', ])
def wxmp_config_set_value(request):
	id = request.POST.get("id")
	value = request.POST.get("value")

	try:
		logger.info(u"设置配置[%s]的参数值为[%s]" % (id, value))
		wxmpConfig = WxmpConfig.objects.get(id=id)
		wxmpConfig.value = value
		wxmpConfig.save()
		ret = {"result": 0, "reason": u"保存成功"}
		return HttpResponse(json.dumps(ret), content_type="application/json")
	except:
		logger.exception("")

	ret = {"result": -1, "reason": u"系统异常"}
	return HttpResponse(json.dumps(ret), content_type="application/json")


# ================ 平台配置 ==================
class SmplatConfigGrid(JqGrid):
	model = SmplatConfig  # could also be a queryset
	pager_id = "#wxmp-config-grid-pager"
	fields = ['id',
			  'label',
			  'name',
			  'value',
			  'vtype',
			  'description',
			  'input_options',
			  # 'update_time',
			  'myac'
			  ]

	url = '/smAdmin/sysconf/smplat_conf_list'
	editurl = '/smAdmin/sysconf/smplat_conf_edit'
	caption = u'溯码平台配置'
	colmodel_overrides = {
		'id': {'key': True, 'width': 20, "hidden": True},
		'label': {
			"label": u"标题",
			"sortable": False,

			"search": True,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'text',
			"editoptions": {"size": "32", "maxlength": "64"},

			'width': 100
		},

		'name': {
			"label": u"参数名",
			"sortable": False,

			"search": True,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'text',
			"editoptions": {"size": "32", "maxlength": "64"},

			'width': 100
		},

		'value': {
			"label": u"参数值",
			"sortable": False,

			"search": False,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'textarea',
			"editoptions": {"rows": "5", "cols": "60"},

			'width': 100
		},

		'vtype': {
			"label": u"参数类型",
			# 排序
			"sortable": False,
			"sorttype": 'string',
			# 搜索
			"search": True,
			"stype": "select",
			"searchoptions": {"sopt": ['eq', ], "value": "string:字符串;json:json;int:整数;float:浮点"},
			# 编辑
			'editable': True,
			"edittype": 'select',
			"editoptions": {"value": "string:字符串;json:json;int:整数;float:浮点"},
			# 其他
			'width': 100
		},

		'description': {
			"label": u"描述",
			"sortable": False,

			"search": False,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'textarea',
			"editoptions": {"rows": "5", "cols": "60"},

			'width': 100
		},

		'input_options': {
			"label": u"输入框配置",
			"sortable": False,

			"search": False,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'textarea',
			"editoptions": {"rows": "5", "cols": "60"},

			'width': 100
		},

		'update_time': {
			"label": u"更新时间",
			"sortable": False,

			"search": True,
			"sorttype": 'date',
			"searchoptions": {"sopt": ['le', 'lt', 'gt', 'ge']},

			'editable': False,
			# "edittype": 'text',
			# "editoptions": {"size": "20", "maxlength": "40"},

			'width': 100
		},

		'myac': {
			"label": u"操作",
			'editable': False,
			"width": 80,
			"fixed": True,
			"sortable": False,
			"search": False,
			"resize": False,
			"formatter": 'actions',
			"formatoptions": {"keys": True, "delbutton": True, }
		}
	}


@login_required(login_url="/smAdmin/login")
@permission_required(['submenu.sysconf.smplat_config', ])
def smplat_config(request):
	"""
	:param request:
	:return:
	"""
	grid = SmplatConfigGrid()
	context = {
		"grid_config": grid.get_config(),
	}
	return render(request, "smAdmin/sysconf/smplat_config.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['sysconf.smplat_config.list', ])
def smplat_config_list(request):
	grid = SmplatConfigGrid()
	return HttpResponse(grid.get_json(request), content_type="application/json")


@login_required(login_url="/smAdmin/login")
@permission_required(['sysconf.smplat_config.add', 'sysconf.smplat_config.edit', 'sysconf.smplat_config.del'])
def smplat_config_edit(request):
	"""
	编辑
	:param request:
	:return:
	"""
	grid = SmplatConfigGrid()

	oper = request.POST.get('oper')
	id = request.POST.get('id')
	user = get_user(request)

	if oper == 'edit':
		if not user.has_perm("sysconf.smplat_config.edit"):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.edit_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'add':
		if not user.has_perm("sysconf.smplat_config.add"):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.add_object(request):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'del':
		if not user.has_perm("sysconf.smplat_config.del"):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.delete_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)

	return HttpResponse(content_type="application/x-javascript", status=406)


@login_required(login_url="/smAdmin/login")
@permission_required(['sysconf.smplat_config.edit', ])
def smplat_config_detail(request):
	"""
	扫描记录详情
	:param request:
	:return:
	"""
	id = request.GET.get('id')

	smplatConfig = SmplatConfig.objects.get(id=id)

	try:
		value_config = json.loads(smplatConfig.input_options)
	except:
		value_config = {}
		logger.exception("")

	input_type = value_config.get("type", "textarea")

	field_info = {
		"fields": [
			{"name": "id", "label": u"Id", "value": smplatConfig.id},
			{"name": "label", "label": u"标题", "value": smplatConfig.label},
			{"name": "name", "label": u"参数名", "value": smplatConfig.name},
			{"name": "value", "label": u"参数值", "value": smplatConfig.value},
			{"name": "vtype", "label": u"值类型", "value": smplatConfig.vtype},
			{"name": "description", "label": u"描述", "value": smplatConfig.description},
			{"name": "input_options", "label": u"输入框配置", "value": smplatConfig.input_options},
			{"name": "update_time", "label": u"更新时间", "value": smplatConfig.update_time}
		],
		"input_type": input_type,
		"value_config": value_config,
		"value_data": smplatConfig.value,
	}

	context = {
		"field_info": field_info,
	}
	return render(request, "smAdmin/sysconf/smplat_config_detail.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['sysconf.smplat_config.edit', ])
def smplat_config_set_value(request):
	id = request.POST.get("id")
	value = request.POST.get("value")

	try:
		logger.info(u"设置配置[%s]的参数值为[%s]" % (id, value))
		smplatConfig = SmplatConfig.objects.get(id=id)
		smplatConfig.value = value
		smplatConfig.save()
		ret = {"result": 0, "reason": u"保存成功"}
		return HttpResponse(json.dumps(ret), content_type="application/json")
	except:
		logger.exception("")

	ret = {"result": -1, "reason": u"系统异常"}
	return HttpResponse(json.dumps(ret), content_type="application/json")


# ================ 后台配置 ==================
class SmadminConfigGrid(JqGrid):
	model = SmadminConfig  # could also be a queryset
	pager_id = "#wxmp-config-grid-pager"
	fields = ['id',
			  'label',
			  'name',
			  'value',
			  'vtype',
			  'description',
			  'input_options',
			  # 'update_time',
			  'myac'
			  ]

	url = '/smAdmin/sysconf/smadmin_conf_list'
	editurl = '/smAdmin/sysconf/smadmin_conf_edit'
	caption = u'溯码后台配置'
	colmodel_overrides = {
		'id': {'key': True, 'width': 20, "hidden": True},
		'label': {
			"label": u"标题",
			"sortable": False,

			"search": True,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'text',
			"editoptions": {"size": "32", "maxlength": "64"},

			'width': 100
		},

		'name': {
			"label": u"参数名",
			"sortable": False,

			"search": True,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'text',
			"editoptions": {"size": "32", "maxlength": "64"},

			'width': 100
		},

		'value': {
			"label": u"参数值",
			"sortable": False,

			"search": False,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'textarea',
			"editoptions": {"rows": "5", "cols": "60"},

			'width': 100
		},

		'vtype': {
			"label": u"参数类型",
			# 排序
			"sortable": False,
			"sorttype": 'string',
			# 搜索
			"search": True,
			"stype": "select",
			"searchoptions": {"sopt": ['eq', ], "value": "string:字符串;json:json;int:整数;float:浮点"},
			# 编辑
			'editable': True,
			"edittype": 'select',
			"editoptions": {"value": "string:字符串;json:json;int:整数;float:浮点"},
			# 其他
			'width': 100
		},

		'description': {
			"label": u"描述",
			"sortable": False,

			"search": False,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'textarea',
			"editoptions": {"rows": "5", "cols": "60"},

			'width': 100
		},

		'input_options': {
			"label": u"输入框配置",
			"sortable": False,

			"search": False,
			"sorttype": 'string',
			"searchoptions": {"sopt": ['cn', ]},

			'editable': True,
			"edittype": 'textarea',
			"editoptions": {"rows": "5", "cols": "60"},

			'width': 100
		},

		'update_time': {
			"label": u"更新时间",
			"sortable": False,

			"search": True,
			"sorttype": 'date',
			"searchoptions": {"sopt": ['le', 'lt', 'gt', 'ge']},

			'editable': False,
			# "edittype": 'text',
			# "editoptions": {"size": "20", "maxlength": "40"},

			'width': 100
		},

		'myac': {
			"label": u"操作",
			'editable': False,
			"width": 80,
			"fixed": True,
			"sortable": False,
			"search": False,
			"resize": False,
			"formatter": 'actions',
			"formatoptions": {"keys": True, "delbutton": True, }
		}
	}


@login_required(login_url="/smAdmin/login")
@permission_required(['submenu.sysconf.smadmin_config', ])
def smadmin_config(request):
	"""
	:param request:
	:return:
	"""
	grid = SmadminConfigGrid()
	context = {
		"grid_config": grid.get_config(),
	}
	return render(request, "smAdmin/sysconf/smadmin_config.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['sysconf.smadmin_config.list', ])
def smadmin_config_list(request):
	grid = SmadminConfigGrid()
	return HttpResponse(grid.get_json(request), content_type="application/json")


@login_required(login_url="/smAdmin/login")
@permission_required(['sysconf.smadmin_config.add', 'sysconf.smadmin_config.edit', 'sysconf.smadmin_config.del'])
def smadmin_config_edit(request):
	"""
	编辑
	:param request:
	:return:
	"""
	grid = SmadminConfigGrid()

	oper = request.POST.get('oper')
	id = request.POST.get('id')
	user = get_user(request)

	if oper == 'edit':
		if not user.has_perm("sysconf.smadmin_config.edit"):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.edit_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'add':
		if not user.has_perm("sysconf.smadmin_config.add"):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.add_object(request):
			return HttpResponse(content_type="application/x-javascript", status=200)
	elif oper == 'del':
		if not user.has_perm("sysconf.smadmin_config.del"):
			return HttpResponse(content_type="application/x-javascript", status=420)
		if not id:
			return HttpResponse(content_type="application/x-javascript", status=420)
		if grid.delete_object(request, id):
			return HttpResponse(content_type="application/x-javascript", status=200)

	return HttpResponse(content_type="application/x-javascript", status=406)


@login_required(login_url="/smAdmin/login")
@permission_required(['sysconf.smadmin_config.edit', ])
def smadmin_config_detail(request):
	"""
	扫描记录详情
	:param request:
	:return:
	"""
	id = request.GET.get('id')

	smadminConfig = SmadminConfig.objects.get(id=id)

	try:
		value_config = json.loads(smadminConfig.input_options)
	except:
		value_config = {}
		logger.exception("")

	input_type = value_config.get("type", "textarea")

	field_info = {
		"fields": [
			{"name": "id", "label": u"Id", "value": smadminConfig.id},
			{"name": "label", "label": u"标题", "value": smadminConfig.label},
			{"name": "name", "label": u"参数名", "value": smadminConfig.name},
			{"name": "value", "label": u"参数值", "value": smadminConfig.value},
			{"name": "vtype", "label": u"值类型", "value": smadminConfig.vtype},
			{"name": "description", "label": u"描述", "value": smadminConfig.description},
			{"name": "input_options", "label": u"输入框配置", "value": smadminConfig.input_options},
			{"name": "update_time", "label": u"更新时间", "value": smadminConfig.update_time}
		],
		"input_type": input_type,
		"value_config": value_config,
		"value_data": smadminConfig.value,
	}

	context = {
		"field_info": field_info,
	}
	return render(request, "smAdmin/sysconf/smadmin_config_detail.html", context=context)


@login_required(login_url="/smAdmin/login")
@permission_required(['sysconf.smadmin_config.edit', ])
def smadmin_config_set_value(request):
	id = request.POST.get("id")
	value = request.POST.get("value")

	try:
		logger.info(u"设置配置[%s]的参数值为[%s]" % (id, value))
		smadminConfig = SmadminConfig.objects.get(id=id)
		smadminConfig.value = value
		smadminConfig.save()
		ret = {"result": 0, "reason": u"保存成功"}
		return HttpResponse(json.dumps(ret), content_type="application/json")
	except:
		logger.exception("")

	ret = {"result": -1, "reason": u"系统异常"}
	return HttpResponse(json.dumps(ret), content_type="application/json")
